package trong.gold.soft.com.model;

import java.io.*;
import javax.microedition.rms.RecordStore;

public class Record
{

    private static RecordStore rs;

    public Record()
    {
    }

    public static void open()
    {
        try
        {
            rs = RecordStore.openRecordStore(Resources.QRS, true);
        }
        catch(Exception e) { }
    }

    public static void close()
    {
        try
        {
            rs.closeRecordStore();
        }
        catch(Exception e) { }
    }

    public static void delete()
    {
        if(RecordStore.listRecordStores() != null)
            try
            {
                RecordStore.deleteRecordStore(Resources.QRS);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
    }

    public static void save()
    {
        try
        {
            ByteArrayOutputStream arrBytes = new ByteArrayOutputStream();
            DataOutputStream Data = new DataOutputStream(arrBytes);
            for(int i = 0; i < 5; i++)
            {
                Data.writeUTF(Resources.name[i]);
                Data.writeUTF(String.valueOf(Resources.score[i]));
                Data.flush();
                byte b[] = arrBytes.toByteArray();
                if(rs.getNumRecords()<5)
                	rs.addRecord(b, 0, b.length);
                else
                	rs.setRecord(i+1, b, 0, b.length);
                arrBytes.reset();
            }

            arrBytes.close();
            Data.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void load()
    {
        try
        {
        	byte[] recData = new byte[50];
        	ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);
        	DataInputStream strmDataType = new DataInputStream(strmBytes);
        	for (int i = 1; i <= rs.getNumRecords(); i++){
        		rs.getRecord(i, recData, 0);
        		String n = strmDataType.readUTF();
        		Resources.name[i-1] = n;
        		String scr = strmDataType.readUTF();
        		
        		Resources.score[i-1]=Integer.parseInt(scr);
        		System.out.println(Resources.score[i-1]);
        		strmBytes.reset();
         	}

        	strmBytes.close();
        	strmDataType.close();
        }
        catch(Exception e)
        {
        	e.printStackTrace();
        }
    }

    public static String getLevel(int x)
    {
        return String.valueOf(x);
    }
}